package com.raylu.util

import com.alibaba.druid.pool.{DruidDataSource, DruidPooledConnection}
import com.alibaba.fastjson.JSONObject

import java.sql.{Connection, DriverManager, ResultSet, ResultSetMetaData, Statement}
import java.util.{Base64, Properties}
import scala.collection.mutable
import scala.collection.mutable.ListBuffer

/**
 *
 * Description:
 *
 * Create by lucienoz on 2021/11/28.
 * Copyright © 2021 lucienoz. All rights reserved.
 */
object MySqlUtil {
	private var druidDataSource : DruidDataSource = null
	private val properties : Properties = PropertiesUtil.load ( "config.properties" )

	def getConnectionFromPool : Connection = {
		if (druidDataSource == null) {
			druidDataSource = new DruidDataSource ()
			druidDataSource.setUrl ( properties.getProperty ( "db.url" ) )
			druidDataSource.setUsername ( new String ( Base64.getDecoder.decode ( properties.getProperty ( "db.username" ) ) ) )
			druidDataSource.setPassword ( new String ( Base64.getDecoder.decode ( properties.getProperty ( "db.password" ) ) ) )
			druidDataSource.setInitialSize ( properties.getProperty ( "db.pool.setInitialSize" ).toInt )
			druidDataSource.setMaxActive ( properties.getProperty ( "db.pool.setMaxActive" ).toInt )
			druidDataSource.setMaxWait ( properties.getProperty ( "db.pool.setMaxWait" ).toInt )
		}
		druidDataSource.getConnection ().getConnection
	}

	def getConnectionFromJDBC : Connection = {
		val connection : Connection = DriverManager.getConnection ( properties.getProperty ( "db.url" ),
			new String ( Base64.getDecoder.decode ( properties.getProperty ( "db.username" ) ) ),
			new String ( Base64.getDecoder.decode ( properties.getProperty ( "db.password" ) ) ) )
		connection
	}

	def queryList(sql:String):List[JSONObject]={
		val listBuffer : ListBuffer[JSONObject] = mutable.ListBuffer[JSONObject]()
		val conn : Connection = getConnectionFromPool
		val stat : Statement = conn.createStatement ()
		val resultSet : ResultSet = stat.executeQuery ( sql )
		val metaData : ResultSetMetaData = resultSet.getMetaData
		while (resultSet.next ()) {
			val jSONObject : JSONObject = new JSONObject ()
			for(i <- 1 to metaData.getColumnCount){
				jSONObject.put(metaData.getColumnName(i),resultSet.getObject(i))
			}
			listBuffer.append(jSONObject)
		}
		listBuffer.toList
	}

	def main(args : Array[String]) : Unit = {
		val conn : Connection = getConnectionFromJDBC
		val statement : Statement = conn.createStatement ()

		val rs : ResultSet = statement.executeQuery ( "select * from gmall.user_info" )
		val metaData : ResultSetMetaData = rs.getMetaData
		while(rs.next()){
			for(i <- 1 to metaData.getColumnCount){
				print(rs.getObject(i)+"::")

			}
			println()

		}




	}


}
